package com.dingreading.cloud.soms.util;

import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.dto.LoginDataDto;
import com.dingreading.cloud.common.util.CookiesUtil;
import com.dingreading.cloud.common.util.LoginAuthUtil;
import com.dingreading.cloud.common.util.RedisParam;
import com.dingreading.cloud.soms.service.AppProjectService;
import com.dingreading.cloud.soms.util.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 门店员工登录信息
 */
@Component
public class LoginInfoUtil {

    public static LoginInfoUtil util;

    @PostConstruct
    public void init() {
        util = this;
    }

    @Resource
    private AppProjectService appProjectService;

    @Resource
    private RedisService redisService;


    /**
     * 获取redis门店员工登录信息
     */
    public static R<Object> getLoginDto(HttpServletRequest request) {

        try {
            Cookie cookie = CookiesUtil.getCookieByName(request, LoginAuthUtil.DDPB_TOKEN);
            String cookieValue = cookie.getValue();
            String loginStr = (String) util.redisService.get(RedisParam.STAFF_LOGIN + cookieValue);
            LoginDataDto loginDataDto = JSONObject.parseObject(loginStr, LoginDataDto.class);
            if (loginDataDto != null) {
                return R.ok(loginDataDto);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        String htmlUrl = request.getHeader(LoginAuthUtil.HTML_URL);
        String appId = LoginAuthUtil.getAppId(htmlUrl);
        String appSecret = getAppSecret(appId);
        String loginUrl = LoginAuthUtil.getLoginUrl(appId, appSecret, htmlUrl);
        return R.fail(-1, "获取用户信息失败，去登陆", loginUrl);
    }

    /**
     * 获取应用秘钥
     */
    private static String getAppSecret(String appId) {
        String appSecret = (String) util.redisService.get(RedisParam.APP_PROJECT + appId);
        if (StringUtils.isBlank(appSecret)) {
            appSecret = util.appProjectService.getAppSecret(appId);

            if (StringUtils.isNotBlank(appSecret))
                util.redisService.set(RedisParam.APP_PROJECT + appId, appSecret, RedisParam.HOUR_TIME);
        }

        return appSecret;
    }

}
